package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 设备Service业务层处理
 *
 * @author alexis
 * @date 2025-03-05
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public List<ProductVo> allProduct() {
        String str = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_KEY);
        if (StrUtil.isBlank(str)) {
            return new ArrayList<>();
        }
        return JSONUtil.toList(str, ProductVo.class);
    }

    @Override
    public int syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() == 200) {
            List<ProductSummary> products = response.getProducts();
            //存储到redis
            redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products), 60 * 60 * 24, TimeUnit.SECONDS);
        } else {
            throw new RuntimeException("同步产品列表失败");
        }
        return 1;
    }

    @Override
    public void register(DeviceDto deviceDto) {
        validateDevice(deviceDto);
        //IOT平台新增设备
        //秘钥
        String secret = RandomUtil.randomString(16);
        String deviceId = RandomUtil.randomString(16);
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withDeviceId(deviceId);
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        request.withBody(body);
        AuthInfo authInfo = new AuthInfo();
        authInfo.withSecret(secret);
        //不设置未激活的设备超时会被删除
        authInfo.withTimeout(0);
        body.setAuthInfo(authInfo);
        try {
            AddDeviceResponse response = client.addDevice(request);
            if (response.getHttpStatusCode() != 201) {
                throw new BaseException("新增设备失败");
            }
        } catch (Exception e) {
            throw new BaseException("新增设备失败", e.getMessage());
        }
        //数据库新增设备
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(secret);
        boolean save = save(device);
        if (save) {
            //TODO 如果数据库添加失败,平台删除设备
        }
    }

    private void validateDevice(DeviceDto deviceDto) {
        //校验设备标识码是否重复
        Long count = this.lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }
        //校验设备名称是否重复
        count = this.lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //校验相同的位置或老人是否绑定了相同的产品
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("该位置或老人已绑定了相同的产品");
        }
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //从数据库中查询设备数据
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isNull(device)) {
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //从iot平台查询数据库中没有的数据
        ShowDeviceResponse response;
        try {
            ShowDeviceRequest request = new ShowDeviceRequest();
            request.withDeviceId(iotId);
            response = client.showDevice(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("查询设备详情失败");
            }
        } catch (Exception e) {
            throw new BaseException("查询设备详情失败", e.getMessage());
        }
        deviceDetailVo.setDeviceStatus(response.getStatus());
        //日期时区转换
        String activeTimeStr = response.getActiveTime();
        if (StrUtil.isNotBlank(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备上报数据失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        List<Map<String, Object>> list = new ArrayList<>();
        if (CollUtil.isEmpty(shadow)) {
            return list;
        }
        //处理上报时间日期
        LocalDateTime eventTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'")
                .atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        Map<String, Object> map = JSONUtil.toBean(JSONUtil.toJsonStr(shadow.get(0).getReported().getProperties()), Map.class);
        map.forEach((k, v) -> {
            HashMap<String, Object> temp = new HashMap<>();
            temp.put("functionId", k);
            temp.put("value", v);
            temp.put("eventTime", eventTime);
            list.add(temp);
        });
        return list;
    }

    @Override
    public void edit(DeviceDto deviceDto) {
        //校验设备是否存在
        String iotId = deviceDto.getIotId();
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isNull(device)) {
            throw new BaseException("设备不存在");
        }
        Long count;
        /*
        方案一:删除数据库重新添加,需要加事务
        方案二:判断设备信息是否发生改变,改变则校验,校验后更新数据库
        处于性能考虑,以下使用方案二
         */
        //如果设备名称改变,校验设备名称是否重复
        boolean deviceNameSame = StrUtil.equals(deviceDto.getDeviceName(), device.getDeviceName());
        if (!deviceNameSame) {
            count = this.lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
            if (count > 0) {
                throw new BaseException("设备名称重复");
            }
        }

        //如果绑定位置发生了改变,校验相同的位置或老人是否绑定了相同的产品
        if (!(StrUtil.equals(deviceDto.getBindingLocation().toString(), device.getBindingLocation())
                && StrUtil.equals(deviceDto.getProductKey(), device.getProductKey())
                && StrUtil.equals(deviceDto.getPhysicalLocationType().toString(), device.getPhysicalLocationType().toString()))) {
            count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                    .eq(Device::getProductKey, deviceDto.getProductKey())
                    .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                    .count();
            if (count > 0) {
                throw new BaseException("该位置或老人已绑定了相同的产品");
            }
        }

        //IOT平台修改设备,只能修改设备名称,如果设备名称未改变,则不发起请求
        if (!deviceNameSame) {
            UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.withDeviceId(iotId);
            UpdateDevice body = new UpdateDevice();
            body.withDeviceName(deviceDto.getDeviceName());
            AuthInfoWithoutSecret authInfoBody = new AuthInfoWithoutSecret();
            //不设置未激活的设备超时会被删除
            authInfoBody.withTimeout(0);
            body.withAuthInfo(authInfoBody);
            request.withBody(body);
            try {
                log.warn("发起华为IOT修改设备请求");
                UpdateDeviceResponse response = client.updateDevice(request);
                if (response.getHttpStatusCode() != 200) {
                    throw new BaseException("修改设备失败");
                }
            } catch (Exception e) {
                throw new BaseException("修改设备失败", e.getMessage());
            }
        }
        //数据库修改设备
        //只能修改设备名称,设备类型,接入点
        device.setBindingLocation(deviceDto.getBindingLocation().toString());
        device.setDeviceName(deviceDto.getDeviceName());
        device.setPhysicalLocationType(deviceDto.getPhysicalLocationType());
        device.setDeviceDescription(deviceDto.getDeviceDescription());
        device.setLocationType(deviceDto.getLocationType());
        device.setRemark(deviceDto.getRemark());
        this.updateDevice(device);
    }

    @Override
    public void deleteDevice(String iotId) {
        try {
            //IOT删除设备
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.withDeviceId(iotId);
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("IOT删除设备失败");
        }
        //数据库删除设备
        boolean remove = remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (!remove) {
            throw new BaseException("删除设备失败");
        }
    }
}
